import React, { Component } from 'react';
// 1. 创建 UserContext 对象
// 2. 默认值的作用：如果要使用 Context 值的组件不在 Provider 的子级，则使用默认值
const UserContext = React.createContext({
    name: "默认值",
    age: 18
});
const ThemeContext = React.createContext({
    theme: "dark"
});
// 类组件中使用
class Son extends Component {
    render() {
        console.log(this.context)
        return (
            <ThemeContext.Consumer>
                {
                    value => {
                        return (
                            <div>类组件：
                                {this.context.name}
                                {this.context.age}
                                {value.theme}
                            </div>
                        )
                    }
                }
            </ThemeContext.Consumer>
        )
    }
}
Son.contextType = UserContext;

// 函数组件中使用
function Son2() {
    return (
        <UserContext.Consumer>
            {
                value => {
                    return (
                        <ThemeContext.Consumer>
                            {
                                theme => {
                                    return (
                                        <div>函数组件：
                                            {value.name}
                                            {value.age}
                                            {theme.theme}
                                        </div>
                                    )
                                }
                            }
                        </ThemeContext.Consumer>
                    )
                }
            }
        </UserContext.Consumer>
    )
}

class Father extends Component {
    render() {
        return (
            <div>
                <Son />
                <Son2 />
            </div>
        )
    }
}

export default class GrandFather extends Component {
    constructor() {
        super();
        this.state = {
            name: "kobe",
            age: 100
        }
    }
    render() {
        return (
            <div>
                <UserContext.Provider value={this.state}>
                    <ThemeContext.Provider value={{ theme: "light" }}>
                        <Father />
                    </ThemeContext.Provider>
                </UserContext.Provider>
                {/* <Father /> 会使用默认值 */}
            </div>
        )
    }
}
